package com.micro.ai.models.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.models.entity.ModelVendor;
import com.micro.ai.models.service.ModelVendorService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 模型供应商控制器
 * 提供模型供应商的CRUD操作和状态管理功能
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/model-vendors")
@Tag(name = "模型供应商管理", description = "模型供应商的增删改查、状态管理")
public class ModelVendorController {

    @Autowired
    private ModelVendorService modelVendorService;

    /**
     * 创建供应商
     * 
     * @param vendor 供应商信息
     * @return 创建成功的供应商信息
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:vendor:create')")
    @Operation(summary = "创建供应商", description = "创建新的模型供应商，支持OpenAI、Anthropic等主流AI模型供应商")
    public ApiResponse<ModelVendor> create(@Valid @RequestBody ModelVendor vendor) {
        log.info("创建模型供应商请求: tenantId={}, vendorCode={}, vendorName={}", 
                vendor.getTenantId(), vendor.getVendorCode(), vendor.getVendorName());
        // 后端填充创建人
        vendor.setCreatedBy(getCurrentUsername());
        
        ModelVendor result = modelVendorService.create(vendor);
        
        return ApiResponse.success("创建成功", result);
    }

    /**
     * 更新供应商
     * 
     * @param id 供应商ID
     * @param vendor 更新的供应商信息
     * @return 更新后的供应商信息
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:vendor:update')")
    @Operation(summary = "更新供应商", description = "更新模型供应商信息，ID为必填项")
    public ApiResponse<ModelVendor> update(
            @Parameter(description = "供应商ID", required = true) @PathVariable String id,
            @Valid @RequestBody ModelVendor vendor) {
        log.info("更新模型供应商请求: vendorId={}, vendorCode={}", id, vendor.getVendorCode());
        
        ModelVendor result = modelVendorService.update(id, vendor);
        
        return ApiResponse.success("更新成功", result);
    }

    /**
     * 删除供应商
     * 
     * @param id 供应商ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:vendor:delete')")
    @Operation(summary = "删除供应商", description = "删除模型供应商，注意：如果该供应商下存在模型定义，将无法删除")
    public ApiResponse<Void> delete(
            @Parameter(description = "供应商ID", required = true) @PathVariable String id) {
        log.info("删除模型供应商请求: vendorId={}", id);
        
        modelVendorService.delete(id);
        
        return ApiResponse.successVoid("删除成功");
    }

    /**
     * 获取供应商详情
     * 
     * @param id 供应商ID
     * @return 供应商详细信息
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('model:vendor:view')")
    @Operation(summary = "获取供应商详情", description = "根据ID获取供应商详细信息，包括配置信息、认证配置等")
    public ApiResponse<ModelVendor> getById(
            @Parameter(description = "供应商ID", required = true) @PathVariable String id) {
        log.info("查询供应商详情: vendorId={}", id);
        
        ModelVendor vendor = modelVendorService.getById(id);
        if (vendor == null) {
            return ApiResponse.error("404", "供应商不存在");
        }
        
        return ApiResponse.success(vendor);
    }

    /**
     * 分页查询供应商
     * 
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param tenantId 租户ID
     * @param keyword 关键词（搜索供应商名称、代码、描述）
     * @param status 状态（active-活跃，inactive-停用）
     * @return 分页的供应商列表
     */
    @GetMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('model:vendor:view')")
    @Operation(summary = "分页查询供应商", description = "根据条件分页查询供应商列表，支持按租户、关键词、状态筛选")
    public ApiResponse<Page<ModelVendor>> pageQuery(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "20") @RequestParam(defaultValue = "20") int pageSize,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "关键词（支持搜索供应商名称、代码、描述）") @RequestParam(required = false) String keyword,
            @Parameter(description = "状态（active-活跃，inactive-停用）") @RequestParam(required = false) String status) {
        log.info("分页查询供应商: pageNum={}, pageSize={}, tenantId={}, keyword={}, status={}", 
                pageNum, pageSize, tenantId, keyword, status);
        
        Page<ModelVendor> page = modelVendorService.pageQuery(pageNum, pageSize, tenantId, keyword, status);
        
        return ApiResponse.success(page);
    }

    /**
     * 更新供应商状态
     * 
     * @param id 供应商ID
     * @param status 状态值（active-启用，inactive-停用）
     * @return 更新结果
     */
    @PatchMapping("/{id}/status")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:vendor:update')")
    @Operation(summary = "更新供应商状态", description = "启用或停用供应商，停用的供应商将不可用")
    public ApiResponse<Void> updateStatus(
            @Parameter(description = "供应商ID", required = true) @PathVariable String id,
            @Parameter(description = "状态（active-启用，inactive-停用）", required = true) @RequestParam String status) {
        log.info("更新供应商状态请求: vendorId={}, status={}", id, status);
        
        modelVendorService.updateStatus(id, status);
        
        return ApiResponse.successVoid("状态更新成功");
    }

    private String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null ? authentication.getName() : "system";
    }
}
